<?php

namespace addons\kuerp\model;


use think\Exception;
use think\Model;
use traits\model\SoftDelete;
/**
 *联系人表
 */
class Contacts Extends Model {
	use SoftDelete;
    // 表名,不含前缀
    protected $name = 'kuerp_customers_user';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
	protected $deleteTime = 'deletetime';
	protected $field = true;


    public function customers()
    {
        return $this->belongsTo('Customers', 'sid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function customer() {
        return $this->hasOne(Customers::class, 'id', 'sid')->field('id,customer_name');
    }
	//负责人
	public function ownerStaff() {
		return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name');
	}


	/**
	 *
	 */
	public static function getList() {
		return self::where(['owner_staff_id'=>['in',Staff::getMyStaffIds()]])->field('id,name')->select();
	}


	//创建联系人
	public static function createContacts($params) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr( $name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}else{
                if(empty($params[$name])){
                    $params[$name]='';
                }
            }
		}
		$staff                     = Staff::info();
		if($staff){
			// $params['create_staff_id'] = $staff->id;
            // $owner_staff_id = $staff->id;
			// if($params['customers_id']){
			//     $owner_staff_id = Customers::where(array('id'=>$params['customer_id']))->value('owner_staff_id');
            // }
			// $params['owner_staff_id']  = $owner_staff_id;
		}
		//获取客户信息
		$customer = Customers::get($params['customer_id']);
		if (empty($customer)) {
			throw new Exception('客户不存在');
		} else {
			$params['customers_code'] = $customer->customer_code;
		}
		$params['sid'] = $params['customer_id'];
		unset($params['customer_id']);
		$model = new self;
		//判断是否首要联系人
		if ($params['is_first'] == 1) {
			//将其他首要联系人改为非首要
			self::where('sid', $params['sid'])->update(['is_first' => 0]);
			$update_customer = [
				'connet_name' => $params['first_connect_name'],
				'customer_mobile' => $params['first_connect_mobile'],
				'customer_phone' => $params['first_connect_phone'],
				'qq_wx_email' => $params['qq_wx_email'],
				'getgoods_address' => $params['connect_address'],
			];
			$res = Customers::update($update_customer, ['id' => $params['sid']]);
			if (false === $res) {
				// 验证失败 输出错误信息
				throw new Exception('新增失败');
			}
		}

		$model = new self;
        $result = $model->allowField(true)->save($params);

		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}
		$lastId=$model->getLastInsID();

		// $otherModel = new ContactsOther();
		// if ($otherModel->save(['id' => $lastId, 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
		// 	// 验证失败 输出错误信息
		// 	throw new Exception($otherModel->getError());
		// }

		//创建日志
		OperationLog::createLog(OperationLog::CONTACTS_TYPE,$lastId, '创建联系人');
		//新增跟进记录
		Record::quickCreateRecord(Record::CUSTOMER_TYPE, $params['sid'], '新增联系人：' . $params['first_connect_name']);
        OperationLog::createLog(OperationLog::CUSTOMER_TYPE, $params['sid'], '新增联系人：' . $params['first_connect_name']);

		return $lastId;
	}


	//修改联系人
	public static function updateContacts($params, $row=[]) {
		//自定义字段
		$other = [];
		foreach ($params as $name => $val) {
			if (strstr($name,'other_') !== false) {
                if(is_array($val)){
                    $other[$name] = implode(',',$val);
                }else{
                    $other[$name] = $val;
                }
				unset($params[$name]);
			}
//            else{
//                if(empty($params[$name])){
//                    $params[$name]='';
//                }
//            }
		}
		if (empty($row)) {
			$row = self::get($params['id']);
		}
		//判断是否首要联系人
		if ($params['is_first'] == 1) {
			//将其他首要联系人改为非首要
			self::where('sid', $row['sid'])->update(['is_first' => 0]);
			$update_customer = [
				'connet_name' => $params['first_connect_name'],
				'customer_mobile' => $params['first_connect_mobile'],
				'customer_phone' => $params['first_connect_phone'],
				'qq_wx_email' => $params['qq_wx_email'],
				'getgoods_address' => $params['connect_address'],
			];
			$res = Customers::update($update_customer, ['id' => $row['sid']]);
			if (false === $res) {
				// 验证失败 输出错误信息
				throw new Exception('新增失败');
			}
		}
		$model = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $model->save($params, ['id' => $params['id']]);
		if (false === $result) {
			// 验证失败 输出错误信息
			throw new Exception($model->getError());
		}
		return true;
	}

	//导入
	public static function importContacts($data) {
		$addContacts = [];
		$addOther     = [];
		foreach ($data as $params) {
			//自定义字段
			$other = [];
			foreach ($params as $name => $val) {
				if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
					unset($params[$name]);
				}else{
                    if(empty($params[$name])){
                        $params[$name]=NULL;
                    }
                }
			}
            $params['createtime'] = time();
            $params['next_time']   = date('Y-m-d H:i:s');
			$other['id']           = $params['id'];
			$addOther[]            = ['id' => $params['id'], 'otherdata' => json_encode($other, JSON_UNESCAPED_UNICODE)];
			$addContacts[]        = $params;
		}

		$model = new self;
		// 调用当前模型对应的User验证器类进行数据验证
		$result = $model->allowField(true)->insertAll($addContacts);

		$otherModel = new ContactsOther();
		$otherModel->allowField(true)->insertAll($addOther);

		return true;
	}

    //获取联系人相关信息
    public function contactsOther() {
        return $this->belongsTo(ContactsOther::class,'id','id');
    }

    public function getUpdatetimeAttr($value) {
        if ($value) {
            return date('Y-m-d H:i', $value);
        }

        return $value;
    }
}
